package top.zhangjianyong.tools.service.api.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.zhangjianyong.tools.parm.wechat.WechatRequestMessage;
import top.zhangjianyong.tools.parm.wechat.WechatResponseMessage;
import top.zhangjianyong.tools.service.api.WechatService;
import top.zhangjianyong.tools.utils.SignatureUtil;
import top.zhangjianyong.tools.wechat.WechatChat;
import top.zhangjianyong.tools.wechat.WechatContentHolder;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author zhangjianyong
 * @since 2025/3/18 下午12:51
 */
@Slf4j
@Service
public class WechatServiceImpl implements WechatService {

    @Value("${wechat.token}")
    private String token;
    @Autowired
    private WechatChat wechatChat;

    @Override
    public Long revice(Map<String, String> params) {
        return signature(params) ? Long.parseLong(params.get("echostr")) : 0L;
    }

    private boolean signature(Map<String, String> params) {
        String signature = params.get("signature");
        String timestamp = params.get("timestamp");
        String nonce = params.get("nonce");
        LocalDateTime localDateTime = LocalDateTimeUtil.of(Long.parseLong(timestamp) * 1000);
        LocalDateTime now = LocalDateTime.now().plusMinutes(-3);
        if (localDateTime.isBefore(now)) {
            log.info("时间戳过期，{}-{}", localDateTime, now);
            return false;
        }
        String sha1 = SignatureUtil.sha1(token, timestamp, nonce);
        return signature.equals(sha1);
    }

    @Override
    public String reviceMessage(Map<String, String> params, WechatRequestMessage message) {
        if (!signature(params)) return "fail";
        String msgType = message.getMsgType();
        String result = "success";
     /*   if ("text".equals(msgType)) {
            //文本消息
            WechatResponseMessage response = wechatChat.call(message);
            result = response.toXml();
        } else if ("event".equals(msgType)) {
            //事件
            if ("subscribe".equals(message.getEvent())) {
                //订阅
                WechatResponseMessage response = message.response("我是小小A，一个聊天机器人，请问我能帮到您什么？");
                result = response.toXml();
            } else if ("unsubscribe".equals(message.getEvent())) {
                WechatContentHolder.remove(message.getFromUserName());
            }
        }
        log.info("回复消息：{}", result);*/
        return result;
    }
}
